package com.youxuan.ssyx.acl.utils;

import com.youxuan.ssyx.model.acl.Permission;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuyang
 */
public class PermissionHelper {
    public static List<Permission> buildPermission(List<Permission> allList) {
        // 创建最终的数据封装集合
        List<Permission> trees = new ArrayList<>();

        // 遍历所有菜单 List 集合，得到第一层数据
        for (Permission permission:allList) {
            if(permission.getPid() == 0) {
                permission.setLevel(1);
                // 调用方法从第一层开始往下找
                trees.add(findChildren(permission,allList));
            }
        }

        return trees;
    }

    /**
     * 递归查找子节点
     * @param permission {上层节点}
     * @param allList {所有菜单数据}
     * @return
     */
    private static Permission findChildren(Permission permission, List<Permission> allList) {
        permission.setChildren(new ArrayList<>());
        // 遍历 allList 所有数据菜单
        for (Permission it: allList) {
            if(it.getPid().longValue() == permission.getId().longValue()) {
               int level = permission.getLevel() + 1;
               it.setLevel(level);

               if (permission.getChildren() == null) {
                   permission.setChildren(new ArrayList<>());
               }

               permission.getChildren().add(findChildren(it,allList));
            }
        }

        return permission;
    }
}
